package cc.rengu.igas.bomp.core.service.trans;

import cc.rengu.igas.bomp.common.dao.UserApexInfoMapper;
import cc.rengu.igas.bomp.common.dao.UserInfoMapper;
import cc.rengu.igas.bomp.common.dao.impl.UserApexInfoMapperImpl;
import cc.rengu.igas.bomp.common.dao.impl.UserInfoMapperImpl;
import cc.rengu.igas.bomp.common.entity.UserApexInfo;
import cc.rengu.igas.bomp.common.entity.UserInfo;
import cc.rengu.igas.bomp.common.enums.RespCodeEnum;
import cc.rengu.igas.bomp.core.service.base.ManageService;
import cc.rengu.igas.bomp.facade.bean.UserApexInfoBean;
import cc.rengu.igas.bomp.facade.request.UserInfoManageRequest;
import cc.rengu.igas.bomp.facade.response.UserInfoManageResponse;
import cc.rengu.oltp.service.common.constant.AppConfigConstant;
import cc.rengu.oltp.service.common.constant.AppParamConstant;
import cc.rengu.oltp.service.common.enums.ChannelEnum;
import cc.rengu.oltp.service.model.BizException;
import cc.rengu.oltp.service.model.BizResponse;
import cc.rengu.oltp.utility.util.*;
import com.alibaba.fastjson.JSON;

import java.util.ArrayList;
import java.util.List;

/**
 * 用户信息管理
 * Created by wangcheng on 2021/7/19 15:27
 */
public class UserInfoManageService extends ManageService {
    @Override
    protected Object bizBeforeCust() throws Exception {
        UserInfoManageRequest userInfoManageRequest = new UserInfoManageRequest();
        ConvertUtil.convertOutput(userInfoManageRequest);
        return userInfoManageRequest;
    }

    @Override
    protected BizResponse bizProcessCust(Object request) throws Exception {
        UserInfoManageRequest userInfoManageRequest = (UserInfoManageRequest) request;
        String oprType = userInfoManageRequest.getOprType();

        /* 参数合法性检查 */
        if (StringUtil.isEmptyOrNull(oprType) || null == userInfoManageRequest.getUserInfo()) {
            rglog.error("用户操作类型:<{}>或者用户信息:<{}>为空", oprType, JSON.toJSONString(userInfoManageRequest.getUserInfo()));
            throw new BizException(RespCodeEnum.PARAM_ERROR.getRespCode(), RespCodeEnum.PARAM_ERROR.getRespDesc());
        }

        /* 用户信息及用户附加信息转换 */
        UserInfo userInfo = new UserInfo();
        BeanUtil.beanCopy(userInfoManageRequest.getUserInfo(), userInfo);
        List<UserApexInfo> userApexInfoList = new ArrayList<>();
        if (null != userInfoManageRequest.getUserInfo().getUserApexInfoList()) {
            for (UserApexInfoBean userApexInfoBean : userInfoManageRequest.getUserInfo().getUserApexInfoList()) {
                UserApexInfo userApexInfo = new UserApexInfo();
                BeanUtil.beanCopy(userInfo, userApexInfo);
                BeanUtil.nullValueCopy(userApexInfoBean, userApexInfo);
                userApexInfoList.add(userApexInfo);
            }
        }
        /* 用户类型：00-内管用户，01-商户服务用户，02-收银台用户，03-其它APP用户 */
        if ("MCMP".equals(userInfoManageRequest.getHeader().getChanlId()) || "UPMP".equals(userInfoManageRequest.getHeader().getChanlId())) {
            userInfo.setUserType("00");
        } else if (ChannelEnum.BSPS.getChannelType().equals(userInfoManageRequest.getHeader().getChanlId())) {
            userInfo.setUserType("01");
        } else if (ChannelEnum.OPMS.getChannelType().equals(userInfoManageRequest.getHeader().getChanlId())) {
            userInfo.setUserType("02");
        } else {
            userInfo.setUserType("03");
        }
        /* 用户登陆ID赋默认值 */
        if (StringUtil.isEmptyOrNull(userInfo.getLoginId())) {
            userInfo.setLoginId("LOGINID");
        }

        /* 根据操作类型登记或者更新用户信息 */
        UserInfoMapper userInfoMapper = new UserInfoMapperImpl();
        UserApexInfoMapper userApexInfoMapper = new UserApexInfoMapperImpl();
        switch (oprType) {
            case "00":
                userInfo.setId(RandomUtil.getUUID());
                userInfo.setOrgCode(userInfo.getUserInst());
                userInfo.setOprId(userInfoManageRequest.getHeader().getChanlId());
                userInfo.setCreateTime(DateUtil.getCurrentDateTime("YYYY-MM-DD hh:mm:ss.SSS"));
                userApexInfoList.forEach(item -> item.setPropertyStatus(AppParamConstant.YES));
                break;
            case "01":
                UserInfo userInfoTmp = userInfoMapper.selectUserInfoByPrimaryKey(userInfo.getInstId(), userInfo.getUserId());
                if (null != userInfoTmp) {
                    BeanUtil.beanCopy(userInfoTmp, userInfo);
                    userInfo.setLastUpdateTime(DateUtil.getCurrentDateTime("YYYY-MM-DD hh:mm:ss.SSS"));
                    if (!userApexInfoList.isEmpty()) {
                        for (UserApexInfo userApexInfo : userApexInfoList) {
                            UserApexInfo userApexInfoTmp = userApexInfoMapper.selectUserApexInfoByPrimaryKey(userInfo.getInstId(), userInfo.getUserId(), userInfo.getUserType(), userApexInfo.getPropertyKey());
                            if (null != userApexInfoTmp) {
                                BeanUtil.nullValueCopy(userInfoTmp, userApexInfo);
                                userApexInfo.setLastUpdateTime(userInfo.getLastUpdateTime());
                            }
                        }
                    }
                }
                break;
            case "02":
                userInfo.setLastUpdateTime(DateUtil.getCurrentDateTime("YYYY-MM-DD hh:mm:ss.SSS"));
                userApexInfoList.forEach(item -> item.setPropertyStatus(AppParamConstant.NO));
                break;
            default:
                rglog.error("不支持的用户信息查询方式:<{}>", oprType);
                throw new BizException(RespCodeEnum.NOT_SUPPORT_ORT_TYPE.getRespCode(), RespCodeEnum.NOT_SUPPORT_ORT_TYPE.getRespDesc());
        }

        /* 登记或者更新用户信息 */
        if (StringUtil.isEmptyOrNull(userInfo.getUserStatus())) {
            if ("00".equals(oprType)) {
                userInfo.setUserStatus("00");
            } else if ("02".equals(oprType)) {
                userInfo.setUserStatus("01");
            }
        }
        userInfoManage(oprType, userInfo, userApexInfoList);

        /* 组装应答报文 */
        BizResponse bizResponse = new BizResponse();
        bizResponse.setRspSysId(AppParamConstant.SYS_ID);
        bizResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
        bizResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());
        return bizResponse;
    }

    @Override
    protected void bizAfterCust(Object response) throws Exception {
        BizResponse bizResponse = (BizResponse) response;
        UserInfoManageResponse userInfoManageResponse = (UserInfoManageResponse) bizResponse.getResult();
        ConvertUtil.convertInput(userInfoManageResponse);
    }

    private void userInfoManage(String oprType, UserInfo userInfo, List<UserApexInfo> userApexInfoList) throws Exception {
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        String corporation = xmlTreeUtil.getXmlTreeStringValue(AppParamConstant.CORPORATION);
        String dbPoolName = XmlConfigUtil.getXmlConfigCacheKeyValue(AppParamConstant.DATABASE_CONF_NODE, AppConfigConstant.MCMP_POOL_NAME);
        if (null != corporation && !corporation.isEmpty()) {
            String dbPoolCashNode = corporation.trim() + AppParamConstant.DATABASE_CONF_NODE;
            dbPoolName = XmlConfigUtil.getXmlConfigCacheKeyValue(dbPoolCashNode, AppConfigConstant.MCMP_POOL_NAME);
        }
        /* 开启数据库事务 */
        DbsUtil dbsUtil = new DbsUtil(dbPoolName);
        dbsUtil.dbsBeginTransaction();
        /* 用户信息管理操作 */
        UserInfoMapper userInfoMapper = new UserInfoMapperImpl();
        UserApexInfoMapper userApexInfoMapper = new UserApexInfoMapperImpl();
        int iReturnCode;
        if ("00".equals(oprType)) {
            iReturnCode = userInfoMapper.insertUserInfo(userInfo);
            if (0 == iReturnCode) {
                for (UserApexInfo userApexInfo : userApexInfoList) {
                    iReturnCode = userApexInfoMapper.insertUserApexInfo(userApexInfo);
                    if (0 != iReturnCode) {
                        rglog.error("登记用户信息失败!");
                        dbsUtil.dbsEndTransaction(false);
                        throw new BizException(RespCodeEnum.DATABASE_OPR_ERROR.getRespCode(), RespCodeEnum.DATABASE_OPR_ERROR.getRespDesc());
                    }
                }
            } else {
                rglog.error("登记用户信息失败!");
                dbsUtil.dbsEndTransaction(false);
                throw new BizException(RespCodeEnum.DATABASE_OPR_ERROR.getRespCode(), RespCodeEnum.DATABASE_OPR_ERROR.getRespDesc());
            }
        } else {
            iReturnCode = userInfoMapper.updateUserInfoByPrimaryKey(userInfo);
            if (0 == iReturnCode) {
                for (UserApexInfo userApexInfo : userApexInfoList) {
                    iReturnCode = userApexInfoMapper.updateUserApexInfoByPrimaryKey(userApexInfo);
                    if (0 != iReturnCode) {
                        rglog.error("更新用户信息失败!");
                        dbsUtil.dbsEndTransaction(false);
                        throw new BizException(RespCodeEnum.DATABASE_OPR_ERROR.getRespCode(), RespCodeEnum.DATABASE_OPR_ERROR.getRespDesc());
                    }
                }
            } else {
                rglog.error("更新用户信息失败!");
                dbsUtil.dbsEndTransaction(false);
                throw new BizException(RespCodeEnum.DATABASE_OPR_ERROR.getRespCode(), RespCodeEnum.DATABASE_OPR_ERROR.getRespDesc());
            }
        }
        /* 结束数据库事务 */
        dbsUtil.dbsEndTransaction(true);
    }
}
